//
//  HighlightViewController.m
//  ReadDemo
//
//  Created by YPShao on 2017/12/18.
//  Copyright © 2017年 YPShao. All rights reserved.
//

#import "HighlightViewController.h"

@interface HighlightViewController ()

@property (nonatomic, strong) UITextView *textView;

@end

@implementation HighlightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    [self setUpView];
    
    NSString *text = @"君不见，黄河之水天上来，奔流到海不复回。君不见，高堂明镜悲白发，朝如青丝暮成雪！人生得意须尽欢，莫使金樽空对月。天生我材必有用，千金散尽还复来。";
    NSArray *keyWords = @[@"不见",@"生",@"对"];
    
    self.textView.attributedText = [self setAttributedText:text withRegularExpression:[self expressionForDefinitionWithPattern:[self regularPattern:keyWords]] attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) setUpView
{
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 80, self.view.frame.size.width, 500)];
    self.textView = textView;
    [self.view addSubview:textView];

}

/**
 * 关键字高亮设置
 */
- (NSMutableAttributedString *)setAttributedText:(NSString *)text
                           withRegularExpression:(NSRegularExpression *)expression
                                      attributes:(NSDictionary *)attributesDict
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [expression enumerateMatchesInString:text
                                 options:0
                                   range:NSMakeRange(0, [text length])
                              usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                                  NSRange matchRange = [result range];
                                  if (attributesDict) {
                                      [attributedString addAttributes:attributesDict range:matchRange];
                                  }
                                  if ([result resultType] == NSTextCheckingTypeLink) {
                                      NSURL *url = [result URL];
                                      [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                  }
                              }];
    return attributedString;
    
}

/**
 * 关键字 正则判断
 */
-(NSString *)regularPattern:(NSArray *)keys
{
    NSMutableString *pattern = [[NSMutableString alloc]initWithString:@"(?i)"];
    for (NSString *key in keys) {
        [pattern appendFormat:@"%@|",key];
    }
    return pattern;
}

-(NSRegularExpression *)expressionForDefinitionWithPattern:(NSString *)pattern
{
    NSRegularExpression *expression = nil;
    expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    return expression;
}

@end
